package com.tcenter.dao.providers.impl;

import com.tcenter.dao.providers.BaseDAO;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * User: Andrey Pautov
 * Date: 5/26/13
 */
@Repository("baseDAO")
@Scope("request")
public abstract class BaseDAOImpl<T> implements BaseDAO<T> {

    @Autowired
    private SessionFactory sessionFactory;

    private Class<T> entityClass;


    public BaseDAOImpl() {}

    @SuppressWarnings("unchecked")
    public BaseDAOImpl(Class<T> entityClass) {
        this.entityClass = entityClass;
    }


    @Override
    public void save(T entity) {
        getCurrentSession().save(entity);
    }

    @Override
    public void update(T entity) {
        getCurrentSession().update(entity);
    }

    @Override
    public void delete(T entity) {
        getCurrentSession().delete(entity);
    }

    @Override
    @SuppressWarnings("unchecked")
    public T getById(Integer id) {
        return (T) getCurrentSession().get(entityClass, id);
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<T> getAll(String tableName) {
        return getCurrentSession().createQuery("from " + tableName).list();
    }


    public Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

}
